package cn.cloud.all.ribbon.rule;

import cn.cloud.all.ribbon.server.Server;
import cn.cloud.all.ribbon.loadbalancer.ILoadBalancer;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class RandomRule extends AbstractLoadBalancerRule {

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    private Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        while (true) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> allList = lb.getAllServers();
            List<Server> upList = lb.getReachableServers();
            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }
            int index = chooseRandomInt(serverCount);
            Server server = upList.get(index);
            if (server == null) {
                Thread.yield();
                continue;
            }
            if (server.isAlive()) {
                return server;
            }
            Thread.yield();
        }
    }

    private int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public static void main(String[] args) {
        int index = ThreadLocalRandom.current().nextInt(10);
        System.out.println(index);
    }
}
